<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <el-form-item label="创建时间">
          <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始时间" />
          —
          <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束时间" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
        <el-popover v-model:visible="deleteVisible" placement="top" width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
            <el-button type="primary" @click="deleteSelectedRow">确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
          </template>
        </el-popover>
      </div>

      <el-table
        ref="multipleTable"
        style="width: 100%"
        border
        :header-cell-style="{background:'#a3c6d2',color:'#849ba1'}"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="编码" prop="ID" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="名称" prop="name" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="dsn" prop="dsn" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="主题" prop="topic" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="分区" prop="Partition" :show-overflow-tooltip="true" />

        <el-table-column align="left" label="数据库名" prop="dbName" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="数据表名" prop="tbName" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="字段映射" prop="FldMap" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="测试结果" prop="testResult" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="配置检查" prop="ready" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="是否启用" prop="enable" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="是否开始" prop="start" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="运行状态" prop="running" :show-overflow-tooltip="true">
        <template #default="scope">{{ getKafkaRunning(scope.row.bsm) }}</template>
        </el-table-column>
        <el-table-column align="left" label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button v-if="getKafkaRunning(scope.row.bsm)=== '未运行' && scope.row.ready === '连接正常' && scope.row.enable === true" type="primary" link icon="CaretRight" class="table-button" @click="clickStartOdsKafka(scope.row)">开 始</el-button>
            <el-button v-if="getKafkaRunning(scope.row.bsm)=== '运行中'" type="primary" link icon="CircleCloseFilled" class="table-button" @click="clickStopOdsKafka(scope.row)">停 止</el-button>
            <el-button type="primary" link icon="edit" class="table-button" @click="updateOdsKafkaFunc(scope.row)">变更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="弹窗操作" class="dialog-mid">
      <el-form ref="elFormRef" :model="formData" label-position="right" :rules="rule" class="x-form" :inline="true">
        <el-form-item label="编码:" prop="ID">
          <el-input v-model="formData.ID" :disabled="true" />
        </el-form-item>
        <el-form-item label="名称:" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="dsn:" prop="dsn">
          <el-input v-model="formData.dsn" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="主题:" prop="topic">
          <el-input v-model="formData.topic" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="指定分区:" prop="partition">
          <el-input v-model="formData.partition" placeholder="默认全部分分区" :disabled="true" />
        </el-form-item>
        <el-form-item label="偏移位:" prop="offset">
          <el-input v-model="formData.offset" placeholder="默认自动记忆" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据库名:" prop="dbName">
          <el-input v-model="formData.dbName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="数据表名:" prop="tbName">
          <el-input v-model="formData.tbName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="字段映射:" prop="fldMap">
          <el-input v-model="formData.fldMap" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="测试结果:" prop="testResult">
          <el-input v-model="formData.testResult" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="是否启用:" prop="enable">
          <el-switch v-model="formData.enable" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="float: left;" type="primary" @click="clickTestConfig">测 试</el-button>
          <el-button v-if="reportOdsKafka !== ''" style="float: left;" type="primary" @click="showReport">测试报告</el-button>
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="clickSave">保 存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogReportVisible" :before-close="closeReport" title="kafka测试报告" class="dialog-small">
      <div style="border: 1px solid #538ea4;margin-top: 10px">
        <span style="white-space: pre-wrap;">{{ reportOdsKafka }}</span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'OdsKafka'
}
</script>

<script setup>
import {
  createOdsKafka,
  deleteOdsKafka,
  deleteOdsKafkaByIds,
  updateOdsKafka,
  findOdsKafka,
  getOdsKafkaList,
  getAllOdsKafkas,
  testOdsKafka, startOdsKafka, stopOdsKafka
} from '@/api/odsKafka'

import { getDictFunc, formatDate, formatBoolean, filterDict } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import {ref, reactive, onUnmounted} from 'vue'
import {startOdsDbJob, stopOdsDbJob} from "@/api/odsDbConfig";
import {getOdsJobRunning} from "@/api/odsJob";

const formData = ref({
})
const reportOdsKafka = ref('')
const rule = reactive({})

const elFormRef = ref()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({
  startCreatedAt: undefined,
  endCreatedAt: undefined,
  apiVersionRequest: undefined
})
const kafkaRunning = ref({})
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  if (searchInfo.value.apiVersionRequest === '') {
    searchInfo.value.apiVersionRequest = null
  }
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
  const table = await getOdsKafkaList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()
const getKafkaRunning = (bsm) => {
  if (Object.keys(kafkaRunning).length > 0) {
    if (bsm in kafkaRunning.value) {
      if (kafkaRunning.value[bsm] === true) {
        return '运行中'
      } else {
        return '未运行'
      }
    } else {
      return '未运行'
    }
  } else {
    return '未运行'
  }
}
const getKafkaStart = (jobStart) => {
  if (jobStart === true) {
    return '启用'
  } else {
    return '停用'
  }
}


const setOptions = async() => {
}

setOptions()

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOdsKafkaFunc(row)
  })
}

const deleteVisible = ref(false)

const deleteSelectedRow = async() => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
  multipleSelection.value.map(item => {
    ids.push(item.ID)
  })
  const res = await deleteOdsKafkaByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    getTableData()
  }
}

const type = ref('')

const updateOdsKafkaFunc = async(row) => {
  const res = await findOdsKafka({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data.reodsKafka
    dialogFormVisible.value = true
  }
}

const deleteOdsKafkaFunc = async(row) => {
  const res = await deleteOdsKafka({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    await getTableData()
  }
}

const dialogFormVisible = ref(false)
const dialogReportVisible = ref(false)
const showReport = () => {
  dialogReportVisible.value = true
}
const closeReport = () => {
  dialogReportVisible.value = false
}
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    bootstrapServers: '',
    sessionTimeoutMs: 0,
    autoOffsetReset: '',
    apiVersionRequest: false,
    brokerVersionFallback: '',
    groupId: '',
    odsTbName: '',
    charSet: '',
    path: '',
    folder: '',
    ftpFileName: '',
    ftpJsonKey: '',
    updateCol: '',
    noCleanList: '',
    diffProc: '',
    newProc: '',
  }
}
const clickTestConfig = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    const res = await testOdsKafka(formData.value)
    reportOdsKafka.value = res.msg
    if (res.code === 0) {
      formData.value.testResult = '测试成功'
      ElMessage({
        type: 'success',
        message: '测试kafka成功'
      })
    } else {
      formData.value.testResult = '测试失败'
    }
  })
}
const clickSave = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createOdsKafka(formData.value)
        break
      case 'update':
        res = await updateOdsKafka(formData.value)
        break
      default:
        res = await createOdsKafka(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      await getTableData()
    }
  })
}
const clickStartOdsKafka = async(data) => {
  const res = await startOdsKafka(data)
  if (res.code === 0) {
    await getTableData()
    await getJobRunningList()
    ElMessage({
      type: 'success',
      message: res.msg
    })
  } else {
    ElMessage({
      type: 'warning',
      message: res.msg
    })
  }
}
const clickStopOdsKafka = async(data) => {
  const res = await stopOdsKafka(data)
  if (res.code === 0) {
    await getTableData()
    await getJobRunningList()
    ElMessage({
      type: 'success',
      message: res.msg
    })
  } else {
    ElMessage({
      type: 'warning',
      message: res.msg
    })
  }
}
const getJobRunningList = async() => {
  const res = await getOdsJobRunning()
  if (res.code === 0) {
    kafkaRunning.value = res.data.jobRunning
  }
}
const timer = ref(null)
timer.value = setInterval(() => {
  getJobRunningList()
}, 1000 * 10)

onUnmounted(() => {
  clearInterval(timer.value)
  timer.value = null
})

</script>

<style>
</style>
